package com.liupaik.pennmarketplace;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Sell extends Activity {

	private EditText etTitle;
	private EditText etText;
	private Spinner cat;
	private Button submit;
	private TextView result;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.sell);

		Spinner spinner = (Spinner) findViewById(R.id.category_spinner);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.category_array, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);

		etTitle = (EditText)findViewById(R.id.title_content);
		etText = (EditText)findViewById(R.id.descrip_content);
		cat = (Spinner)findViewById(R.id.category_spinner);
		submit = (Button) findViewById (R.id.sell_submit_button);
		result = (TextView)findViewById(R.id.result);

		//Set Click Listener
		submit.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				String title = etTitle.getText().toString();
				String text = etText.getText().toString();
				
				if (title.length() == 0){
					new AlertDialog.Builder(Sell.this)	                			  
        			.setMessage("Please provide a title for the listing.")  
        			.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        				public void onClick(DialogInterface dialog, int id) {
        					etTitle.requestFocus();
        				}
        			})
        			.show();
				}
				else if (text.length() == 0){
					new AlertDialog.Builder(Sell.this)	                			  
        			.setMessage("Please provide a description for the listing.")  
        			.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        				public void onClick(DialogInterface dialog, int id) {
        					etText.requestFocus();
        				}
        			})
        			.show();
				}
				
				else {
				
				
				
				
				int c = cat.getSelectedItemPosition();
				SharedPreferences user = getSharedPreferences("Users", MODE_PRIVATE);
		        String id = user.getString("CurrentUser", null);
				
				String r = postlisting(id,title,text,c);
				result.setText(r);
				//Intent myIntent = new Intent(v.getContext(), BuySell.class);
				//startActivityForResult(myIntent, 0);
				finish();
				
				}
			}
		});
	}
	
	public static final String POST = "http://www.upennakpsi.org/lololol/pennmarketplace/postlisting.php"; 

	private String postlisting(String id, String title, String text, int cat) {

		InputStream is = null;

		String returnString = "";

		//the postings
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("title",title));
		nameValuePairs.add(new BasicNameValuePair("text",text));
		nameValuePairs.add(new BasicNameValuePair("cat",Integer.toString(cat)));
		nameValuePairs.add(new BasicNameValuePair("id",id));
		
		//http post
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(POST);
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);            
			HttpEntity entity = response.getEntity();
			is = entity.getContent();                

		}catch(Exception e){
			returnString += "Error in connecting...";
			Log.e("log_tag", "Error in http connection "+e.toString());
		}

		//convert response to string
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			is.close();
			returnString=sb.toString();
		}catch(Exception e){
			//returnString += "\nError in converting...";
			Log.e("log_tag", "Error converting result "+e.toString());
		}

		return returnString;
	}   
    
//    public class MyOnItemSelectedListener implements OnItemSelectedListener {
//
//        public void onItemSelected(AdapterView<?> parent,
//            View view, int pos, long id) {
//          Toast.makeText(parent.getContext(), "The category is " +
//              parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
//        }
//
//        public void onNothingSelected(AdapterView parent) {
//          // Do nothing.
//        }
//    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.menu, menu);
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
		case R.id.preferences:
			startActivity(new Intent(this, Prefs.class));
			return true; 
			
		case R.id.logout:
			//IMPLEMENT LOGOUT HERE
			
			Toast.makeText(
					getApplicationContext(),
					"Successfully Logged Out!",
					Toast.LENGTH_SHORT)
					.show();
			Intent myIntent = new Intent(Sell.this, Intro.class);
			startActivityForResult(myIntent, 0);
			
			
//			new AlertDialog.Builder(Sell.this)
//			//.setTitle(Register.this.getResources().getString(R.string.register_alert))  
//			.setMessage("Successfully Logged Out!")  
//			//.setIcon(R.drawable.book)  
//			.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
//				public void onClick(DialogInterface dialog, int id) {
//					Intent myIntent = new Intent(Sell.this, Intro.class);
//					startActivityForResult(myIntent, 0);
//				}
//			})
//			.show();
			
			return true;
    	}
    	return false;
    }
    
    
}
